//
//  VehicleListViewController.m
//  阿帕
//
//  Created 阿帕 on 2019/12/25.
//  Copyright © 2019 GCY. All rights reserved.
//

#import "CarSourceViewController.h"

#import "CarSourceAddViewController.h"

#import "CarSourceCell.h"

@interface CarSourceViewController ()<UITableViewDelegate, UITableViewDataSource, CarSourceCellButtonDelegate>

@property (strong , nonatomic)UITextField *textFiled;

@property (strong , nonatomic)UITableView *tableView;

@property (strong , nonatomic)NSMutableArray *dataArray;

@property (strong , nonatomic)UIImageView *foundImageView;

@property (strong , nonatomic)UIButton *confirmButton;

@property (nonatomic, assign) NSInteger pageNum;

@end

@implementation CarSourceViewController

static const CGFloat cellHeight = 160;

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [self getCarSourceListRequest];

}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    _pageNum = 1;
    
    [self baseViewSetup];
}

- (void)baseViewSetup {
    
    self.navigationItem.title = @"我的车源";
    
    self.view.backgroundColor = BackgroundColor;
    
    _textFiled = [[UITextField alloc] initWithFrame:CGRectMake(0, 10, ScreenW, 40)];
    _textFiled.font = font(14);
    _textFiled.text = @"";
    _textFiled.backgroundColor = [UIColor whiteColor];
    _textFiled.clearButtonMode = UITextFieldViewModeWhileEditing;
    _textFiled.keyboardType = UIKeyboardTypeDefault;
    _textFiled.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请填写相关信息" attributes:@{NSForegroundColorAttributeName: Light_TextColor}];
    _textFiled.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 15, 40)];
    _textFiled.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 15, 40)];
    _textFiled.leftViewMode = UITextFieldViewModeAlways;
    [_textFiled addSubview: leftView];
    
    
    UIImageView *searchImage = [[UIImageView alloc]initWithFrame:CGRectMake(ScreenW-40, 10, 20, 20)];
    searchImage.userInteractionEnabled = YES;
    searchImage.image = [UIImage imageNamed:@"gcy_icon_search_siji"];
    _textFiled.rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
    _textFiled.rightViewMode = UITextFieldViewModeAlways;
    
    [searchImage nyl_addTapGes:^{
        _pageNum = 1;
        [self getCarSourceListRequest];
    }];
    
    [_textFiled addSubview:searchImage];
    
    [self.view addSubview:_textFiled];
    
    [self.view addSubview:self.tableView];
    
    [self.view addSubview:self.confirmButton];
}

- (void)getCarSourceListRequest {
    WEAKSELF
    
    if (_pageNum == 1) {
        [self.dataArray removeAllObjects];
    }
    
    NSDictionary *pamars = @{
        @"searchInfo": _textFiled.text,
        @"pageSize":DEFULT_LOAD_NUM,
        @"pageNum":[NSNumber numberWithInteger:_pageNum],
        @"token":[UserDefaultUtil valueForKey:USER_TOKEN],
    };
    
    [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-tms-api",[ReAddressDynamic shared].baseUrl], VEHICLE_SOURCE) withParameter:pamars withVC:self netName:@"我的车源列表" success:^(id response, NSString *msg) {
        
        if ([response[@"records"] count] != 0) {
            
            [weakSelf.dataArray addObjectsFromArray:[CarSourceRecordModel mj_objectArrayWithKeyValuesArray:response[@"records"]]];
            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.tableView.mj_footer endRefreshing];
            
            weakSelf.foundImageView.hidden = YES;
            weakSelf.tableView.hidden = NO;
            
        }else{
            if (_pageNum == 1) {
                weakSelf.foundImageView.hidden = NO;
                weakSelf.tableView.hidden = YES;
            }
            
            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
            
        }
        
        [weakSelf.tableView reloadData];
        
    } failure:^(NSInteger code, NSString *msg) {
        
    }];
}

- (void)confirmButtonClick {
    
    CarSourceAddViewController *csavc = [[CarSourceAddViewController alloc] init];
    [self.navigationController pushViewController:csavc animated:YES];
}

#pragma mark - CarSourceCellButtonDelegate
- (void)cellButtonIndexClick:(NSInteger)index withButton:(UIButton *)button {
    
    WEAKSELF
    NSIndexPath *indexpath = [self.tableView indexPathForRowAtPoint:[self.tableView convertPoint:button.center fromView:button.superview]];
    NSLog(@"点击了第%ld个item的第%ld个按钮",(long)indexpath.row, (index-99));
    
    VehicleListModel *model = self.dataArray[indexpath.row];
    
    NSString *title = button.titleLabel.text;
    
    if ([title isEqual:@"编辑"]) {
                
        CarSourceAddViewController *csavc = [[CarSourceAddViewController alloc] init];
        csavc.addType = 1;
        csavc.code = model.code;
        [self.navigationController pushViewController:csavc animated:YES];
        
    } else if ([title isEqual:@"删除"]) {
        
        [DCSpeedy dc_SetUpAlterWithView:self Title:@"" Message:@"确定要删除车源吗？" Sure:^{
            
            NSDictionary *params = @{@"codes": model.code, @"token":[UserDefaultUtil valueForKey:USER_TOKEN],};
            
            [HTTPManager deleteNetworkRequest:CJStringWithFormat(@"%@%@",[NSString stringWithFormat:@"%@/ntocc-tms-api",[ReAddressDynamic shared].baseUrl],VEHICLE_SOURCE) withParameter:params withVC:self netName:@"删除车源" success:^(id response, NSString *msg) {
                
                [XSInfoView showInfo:@"删除成功" onView:weakSelf.view];
                                             
                [weakSelf.dataArray removeObjectAtIndex:indexpath.row];
                [weakSelf.tableView deleteRowsAtIndexPaths:@[indexpath] withRowAnimation:UITableViewRowAnimationAutomatic];
                
            } failure:^(NSInteger code, NSString *msg) {
                
            }];
            
        } Cancel:^{
            
        }];

    }
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CarSourceCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellID"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.delegate = self;
    
    cell.model = self.dataArray[indexPath.row];
    
    return cell;
}

//上拉刷新数据
- (void)loadNewData{
    _pageNum = 1;
    [self getCarSourceListRequest];
}
- (void)loadMoreData{
    _pageNum ++;
    [self getCarSourceListRequest];
}


#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return cellHeight;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.001f;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
}
#pragma mark - LazyLoad
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.frame = CGRectMake(0, 51, ScreenW, ScreenH - NavHeight - 51 - 75);
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        //注册单元格
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([CarSourceCell class]) bundle:nil] forCellReuseIdentifier:@"CellID"];
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    }
    
    return _tableView;
}

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}
- (UIImageView *)foundImageView {
    if (!_foundImageView) {
        _foundImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 170, 170)];
        _foundImageView.image = image(@"gcy_img_list_found");
        _foundImageView.contentMode = UIViewContentModeScaleAspectFit;
        _foundImageView.cy_centerX = self.view.cy_centerX;
        _foundImageView.cy_centerY = self.view.cy_centerY;
        _foundImageView.cy_centerY -= 60;
        [self.view addSubview:_foundImageView];
    }
    return _foundImageView;
}

- (UIButton *)confirmButton {
    if (!_confirmButton) {
        _confirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_confirmButton setTitle:@"新增车源" forState:UIControlStateNormal];
        [_confirmButton setBackgroundColor:Theme_ColorValue];
        cut(_confirmButton, BTN_BORDER_RADIUS);
        [_confirmButton addTarget:self action:@selector(confirmButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [_confirmButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _confirmButton.frame = CGRectMake(20, ScreenH - NavHeight - 65, ScreenW-40, 45);
    }
    return _confirmButton;
}
@end
